<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Utils\Date;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Setting extends Controller
{
    public function setSetting(Request $request)
    {
        if (!$request->input('setting')) {
            return response()->json([
                'code' => 500,
                'msg' => '缺少配置数据',
                'data' => []
            ]);
        }
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => (new \App\Db\Setting())->setSetting($request->input('setting'), $request->siteId)
        ]);
    }

    public function getSetting(Request $request)
    {
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => (new \App\Db\Setting())->getSetting($request->input(null), $request->siteId)
        ]);
    }

    public function exportDbFile()
    {
        return response()->download(
            str_replace('app/Http/Controllers/Admin', '' ,__DIR__) . 'storage/blogsrc/db.sqlite',
            'db.sqlite'
        );
    }

    public function getSettingDir(Request $request)
    {
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => (new \App\Db\Setting())->getSettingDir($request->siteId)
        ]);
    }

    public function getVisitLogOptions()
    {
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => (new \App\Db\Setting())->getVisitLogOptions()
        ]);
    }

    public function getVisitLog(Request $request)
    {
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => (new \App\Db\Setting())->getVisitLog($request->input(null))
        ]);
    }

    public function clearVisitLog(Request $request)
    {
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => (new \App\Db\Setting())->clearVisitLog($request->input(null))
        ]);
    }

    public function getAllThemesFromMarket()
    {
        $themes = [];
        $localThemes = scandir(str_replace('app/Http/Controllers/Admin', 'storage/blogsrc/themes', __DIR__));

        foreach ($localThemes as $vv) {
            if (!in_array($vv, ['.', '..', '.DS_Store']) && !in_array($vv, array_column($themes, 'name'))) {
                $themeJsonFilePath = str_replace('app/Http/Controllers/Admin', 'storage/blogsrc/themes', __DIR__) . "/{$vv}/hikari_theme.json";

                $image = "";
                $defaultConf = [];
                $themeName = '';
                if (file_exists($themeJsonFilePath)) {
                    $themeJson = json_decode(file_get_contents($themeJsonFilePath), true);
                    if (isset($themeJson['image'])) {
                        $image = $themeJson['image'];
                    }
                    if (isset($themeJson['defaultConf'])) {
                        $defaultConf = $themeJson['defaultConf'];
                    }
                    if (isset($themeJson['name'])) {
                        $themeName = $themeJson['name'];
                    }
                }

                $themes[] = [
                    'name' => $vv,
                    'label' => $themeName ?: $vv,
                    'image' => $image,
                    'files' => '',
                    'local' => true,
                    'defaultConf' => $defaultConf
                ];
            }
        }
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => $themes
        ]);
    }

    public function getThemeJson(Request $request)
    {
        if (!$request->input('theme')) {
            return response()->json([
                'code' => 500,
                'msg' => '请选择要查看 json 的主题',
                'data' => []
            ]);
        }
        $theme = $request->input('theme');
        $jsonContent = DB::table('setting')->where([
            'site' => $request->siteId,
            'type' => "theme_json_{$theme}"
        ])->first();
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => $jsonContent
        ]);
    }

    public function saveThemeJson(Request $request)
    {
        if (!$request->input('theme')) {
            return response()->json([
                'code' => 500,
                'msg' => '请选择要保存 json 的主题',
                'data' => []
            ]);
        }
        if (!$request->input('json')) {
            return response()->json([
                'code' => 500,
                'msg' => '请编辑 json',
                'data' => []
            ]);
        }
        $theme = $request->input('theme');

        DB::table('setting')->where([
            'site' => $request->siteId,
            'type' => "theme_json_{$theme}"
        ])->delete();
        $res = DB::table('setting')->insert([
            'site' => $request->siteId,
            'type' => "theme_json_{$theme}",
            'value' => $request->input('json'),
            'order' => 0,
            'create_time' => Date::now()
        ]);
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => ['res' => $res]
        ]);
    }

    public function getSiteList()
    {
        $data = DB::table('site')->where(['is_del' => 0])->get();
        foreach ($data as $k => $v) {
            $v->hosts = explode(',', substr($v->host, 1, strlen($v->host) - 2));
            unset($v->host);
        }
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => $data
        ]);
    }

    public function addSite(Request $request)
    {
        if (!$request->input('name')) {
            return response()->json([
                'code' => 500,
                'msg' => '缺少站点名',
                'data' => []
            ]);
        }
        if (!$request->input('host')) {
            return response()->json([
                'code' => 500,
                'msg' => '缺少站点域名',
                'data' => []
            ]);
        }
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => [
                'res' => $request->input('id') ?
                    DB::table('site')->where(['id' => $request->input('id')])->update([
                        'name' => $request->input('name'),
                        'host' => "," . $request->input('host') . ",",
                    ]):
                    DB::table('site')->insert([
                        'name' => $request->input('name'),
                        'host' => "," . $request->input('host') . ",",
                        'create_time' => Date::now()
                    ])
            ]
        ]);
    }

    public function deleteSite(Request $request)
    {
        if (!$request->input('id')) {
            return response()->json([
                'code' => 500,
                'msg' => '缺少站点 id',
                'data' => []
            ]);
        }
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => [
                'res' => DB::table('site')->where(['id' => $request->input('id')])->update(['is_del' => 1])
            ]
        ]);
    }
}
